import { HttpMethod, HttpRequestService } from '../http';

/**
 * This service is intend to load the config info from json file in public/assets/config directory.
 * https://create-react-app.dev/docs/using-the-public-folder
 */
export class ConfigService {
  protected static readonly basePath: string = `${import.meta.env.BASE_URL}assets/config`;
  protected static localGeneralConfig: any;
  protected static loadingConfigPromise: Promise<void> | null;

  static async getLocalGeneralConfig<T>(
    defaultConfig: T,
    filename: string = 'general-config.json',
  ): Promise<T> {
    // Checks on [localGeneralConfig] to see if need to load config file.
    if (!this.localGeneralConfig) {
      // Checks on [loadingConfigPromise] to see if currently loading is in progress.
      if (!this.loadingConfigPromise) {
        // Creates new promise to load config file.
        this.loadingConfigPromise = (async () => {
          try {
            this.localGeneralConfig =
              (await this.loadLocalGeneralConfig(filename)) ?? defaultConfig;
          } finally {
            this.loadingConfigPromise = null;
          }
        })();
      }

      // Waits for loading to complete.
      await this.loadingConfigPromise;
    }

    return this.localGeneralConfig as T;
  }

  /**
   * Loads local general config data.
   */
  protected static async loadLocalGeneralConfig<T>(filename: string): Promise<T> {
    return (
      await new HttpRequestService().makeOriginalRequest(`${this.basePath}/${filename}`, {
        httpMethod: HttpMethod.get,
      })
    ).payload;
  }
}
